/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package validateipapp;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.lang.Math;
import java.util.Vector;

/**
 * @author Ana Beatriz Johansen
 * 1290371112001
 */
public class ValidateIPMIDlet extends MIDlet implements CommandListener {
    
    private boolean midletPaused = false;

//<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Form Informarform;
    private TextField IPtextField;
    private TextField MascaratextField;
    private StringItem stringItem;
    private Form Validarform;
    private StringItem NETIDstringItem;
    private StringItem BROADstringItem;
    private StringItem VALIDOstringItem;
    private Command exitCommand;
    private Command VerificarCommand;
    private Command backCommand;
//</editor-fold>//GEN-END:|fields|0|
    /**
     * The ValidadeIPMIDlet constructor.
     */
    private String[] split(String original,String separator) {
    //método que separa a string de ip e máscara
    //visto de acordo em: http://stackoverflow.com/questions/657627/split-string-logic-in-j2me    
    Vector nodes = new Vector();
    // Parse nodes into vector
    int index = original.indexOf(separator);
    while(index >= 0) {
        nodes.addElement( original.substring(0, index) );
        original = original.substring(index+separator.length());
        index = original.indexOf(separator);
    }
    // Get the last node
    nodes.addElement( original );

     // Create split string array
    String[] result = new String[ nodes.size() ];
    if( nodes.size() > 0 ) {
        for(int loop = 0; loop < nodes.size(); loop++)
        {
            result[loop] = (String)nodes.elementAt(loop);
            System.out.println(result[loop]);
        }

    }
   return result;
}
    
    public ValidateIPMIDlet() {
    }
    
    public String CalcularIP(int ip, int mascara) {
        //método que calcula a máscara quebrada (diferente de 0 e 255)
        //e resulta na parte quebrada do Net Id
        
        // fórmula para calculo de mascara quebrada
        int c1 = 256 - mascara;
        int c2 = (int) ip / c1;
        int c3 = c2 * c1;  
                               
    return c3+"";
    }
    
    public String CompareIP(String[] ip, String[] id, String[] broad) {
        //método que após o calculo, compara com o Net Id e o Broadcast, 
        //caso seja diferente, o IP será válido. 
        int validacaoNETID=0;
        int validacaoBROAD=0;
        for (int cont=0; cont<4; cont++){
            if(ip[cont].equals(id[cont])){
                validacaoNETID++;
            }
        }
        for (int cont=0; cont<4; cont++){
            if(ip[cont].equals(broad[cont])){
                validacaoBROAD++;
            }
        }
        if (validacaoNETID == 4 || validacaoBROAD == 4)
        return "Não é válido!!! ";
        else 
        return "É válido!!! ";
    }

//<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
//</editor-fold>//GEN-END:|methods|0|
//<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initializes the application. It is called only once when the MIDlet is
     * started. The method is called before the
     * <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
//</editor-fold>//GEN-END:|0-initialize|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getInformarform());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
//</editor-fold>//GEN-END:|3-startMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
//</editor-fold>//GEN-END:|4-resumeMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The
     * <code>display</code> instance is taken from
     * <code>getDisplay</code> method. This method is used by all actions in the
     * design for switching displayable.
     *
     * @param alert the Alert which is temporarily set to the display;
     * if <code>null</code>, then <code>nextDisplayable</code> is set
     * immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
//</editor-fold>//GEN-END:|5-switchDisplayable|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a
     * particular displayable.
     *
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        
        
        
        if (displayable == Informarform) {//GEN-BEGIN:|7-commandAction|1|26-preAction
            if (command == VerificarCommand) {//GEN-END:|7-commandAction|1|26-preAction
                // write pre-action user code here
                switchDisplayable(null, getValidarform());//GEN-LINE:|7-commandAction|2|26-postAction
             
                String IP = IPtextField.getString();
                String Mascara = MascaratextField.getString();
                String n0,n1,n2,n3,b0,b1,b2,b3;
                
                String[] arrayIP = split(IP, "."); 
                // separando os octetos do IP e da Mascara de acordo com o método split             
                String[] arrayMascara = split(Mascara, ".");
                
                //calculando o net id e o broadcast do primeiro octeto
                if (arrayMascara[0].equals("255")){
                    n0 = arrayIP[0];
                }else if(arrayMascara[0].equals("0")){
                    n0 = "0";
                }else{
                    n0 = CalcularIP(Integer.parseInt(arrayIP[0]),Integer.parseInt(arrayMascara[0]));
                }
                b0 = (255 - Integer.parseInt(arrayMascara[0]) + Integer.parseInt(n0))+"";
                
                //calculando o net id e o broadcast do segundo octeto
                if (arrayMascara[1].equals("255")){
                    n1 = arrayIP[1];
                }else if(arrayMascara[1].equals("0")){
                    n1 = "0";
                }else{
                    n1 = CalcularIP(Integer.parseInt(arrayIP[1]),Integer.parseInt(arrayMascara[1]));
                }
                b1 = (255 - Integer.parseInt(arrayMascara[1]) + Integer.parseInt(n1))+"";
                
                //calculando o net id e o broadcast do terceiro octeto
                if (arrayMascara[2].equals("255")){
                    n2 = arrayIP[2];
                }else if(arrayMascara[2].equals("0")){
                    n2 = "0";
                }else{
                    n2 = CalcularIP(Integer.parseInt(arrayIP[2]),Integer.parseInt(arrayMascara[2]));
                }
                b2 = (255 - Integer.parseInt(arrayMascara[2]) + Integer.parseInt(n2))+"";
                
                //calculando o net id e o broadcast do quarto octeto
                if (arrayMascara[3].equals("255")){
                    n3 = arrayIP[3];
                }else if(arrayMascara[3].equals("0")){
                    n3 = "0";
                }else{
                    n3 = CalcularIP(Integer.parseInt(arrayIP[3]),Integer.parseInt(arrayMascara[3]));
                }
                b3 = (255 - Integer.parseInt(arrayMascara[3]) + Integer.parseInt(n3))+"";
                
                //exibindo o Net ID, o Broadcast e validando o IP
                NETIDstringItem.setText(n0+"."+n1+"."+n2+"."+n3); 
                BROADstringItem.setText(b0+"."+b1+"."+b2+"."+b3);
                String[] netidCalc = {n0,n1,n2,n3};
                String[] broadCalc = {b0,b1,b2,b3};
                VALIDOstringItem.setText(CompareIP(arrayIP,netidCalc,broadCalc));
                
            } else if (command == exitCommand) {//GEN-LINE:|7-commandAction|3|21-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|4|21-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|5|32-preAction
        } else if (displayable == Validarform) {
            if (command == backCommand) {//GEN-END:|7-commandAction|5|32-preAction
                // write pre-action user code here
                switchDisplayable(null, getInformarform());//GEN-LINE:|7-commandAction|6|32-postAction
                IPtextField.setString("");
                MascaratextField.setString("");
            }//GEN-BEGIN:|7-commandAction|7|7-postCommandAction
        }//GEN-END:|7-commandAction|7|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|8|
//</editor-fold>//GEN-END:|7-commandAction|8|


//<editor-fold defaultstate="collapsed" desc=" Generated Getter: Informarform ">//GEN-BEGIN:|14-getter|0|14-preInit
    /**
     * Returns an initialized instance of Informarform component.
     *
     * @return the initialized component instance
     */
    public Form getInformarform() {
        if (Informarform == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
            Informarform = new Form("Verifique seu IP", new Item[]{getIPtextField(), getMascaratextField(), getStringItem()});//GEN-BEGIN:|14-getter|1|14-postInit
            Informarform.addCommand(getExitCommand());
            Informarform.addCommand(getVerificarCommand());
            Informarform.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit
            // write post-init user code here
        }//GEN-BEGIN:|14-getter|2|
        return Informarform;
    }
//</editor-fold>//GEN-END:|14-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: IPtextField ">//GEN-BEGIN:|27-getter|0|27-preInit
    /**
     * Returns an initialized instance of IPtextField component.
     *
     * @return the initialized component instance
     */
    public TextField getIPtextField() {
        if (IPtextField == null) {//GEN-END:|27-getter|0|27-preInit
            // write pre-init user code here
            IPtextField = new TextField("Informe o IP:", "", 32, TextField.ANY);//GEN-LINE:|27-getter|1|27-postInit
            // write post-init user code here
        }//GEN-BEGIN:|27-getter|2|
        return IPtextField;
    }
//</editor-fold>//GEN-END:|27-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: MascaratextField ">//GEN-BEGIN:|28-getter|0|28-preInit
    /**
     * Returns an initialized instance of MascaratextField component.
     *
     * @return the initialized component instance
     */
    public TextField getMascaratextField() {
        if (MascaratextField == null) {//GEN-END:|28-getter|0|28-preInit
            // write pre-init user code here
            MascaratextField = new TextField("Informe a m\u00E1scara:", "", 32, TextField.ANY);//GEN-LINE:|28-getter|1|28-postInit
            // write post-init user code here
        }//GEN-BEGIN:|28-getter|2|
        return MascaratextField;
    }
//</editor-fold>//GEN-END:|28-getter|2|





//<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|20-getter|0|20-preInit
    /**
     * Returns an initialized instance of exitCommand component.
     *
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {//GEN-END:|20-getter|0|20-preInit
            // write pre-init user code here
            exitCommand = new Command("Sair", Command.EXIT, 0);//GEN-LINE:|20-getter|1|20-postInit
            // write post-init user code here
        }//GEN-BEGIN:|20-getter|2|
        return exitCommand;
    }
//</editor-fold>//GEN-END:|20-getter|2|



//<editor-fold defaultstate="collapsed" desc=" Generated Getter: VerificarCommand ">//GEN-BEGIN:|25-getter|0|25-preInit
    /**
     * Returns an initialized instance of VerificarCommand component.
     *
     * @return the initialized component instance
     */
    public Command getVerificarCommand() {
        if (VerificarCommand == null) {//GEN-END:|25-getter|0|25-preInit
            // write pre-init user code here
            VerificarCommand = new Command("Calcular", Command.ITEM, 0);//GEN-LINE:|25-getter|1|25-postInit
            // write post-init user code here
        }//GEN-BEGIN:|25-getter|2|
        return VerificarCommand;
    }
//</editor-fold>//GEN-END:|25-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: Validarform ">//GEN-BEGIN:|30-getter|0|30-preInit
    /**
     * Returns an initialized instance of Validarform component.
     *
     * @return the initialized component instance
     */
    public Form getValidarform() {
        if (Validarform == null) {//GEN-END:|30-getter|0|30-preInit
            // write pre-init user code here
            Validarform = new Form("Resultado", new Item[]{getNETIDstringItem(), getBROADstringItem(), getVALIDOstringItem()});//GEN-BEGIN:|30-getter|1|30-postInit
            Validarform.addCommand(getBackCommand());
            Validarform.setCommandListener(this);//GEN-END:|30-getter|1|30-postInit
            // write post-init user code here
        }//GEN-BEGIN:|30-getter|2|
        return Validarform;
    }
//</editor-fold>//GEN-END:|30-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: NETIDstringItem ">//GEN-BEGIN:|35-getter|0|35-preInit
    /**
     * Returns an initialized instance of NETIDstringItem component.
     *
     * @return the initialized component instance
     */
    public StringItem getNETIDstringItem() {
        if (NETIDstringItem == null) {//GEN-END:|35-getter|0|35-preInit
            // write pre-init user code here
            NETIDstringItem = new StringItem("Net ID:", "");//GEN-LINE:|35-getter|1|35-postInit
            // write post-init user code here
        }//GEN-BEGIN:|35-getter|2|
        return NETIDstringItem;
    }
//</editor-fold>//GEN-END:|35-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: BROADstringItem ">//GEN-BEGIN:|36-getter|0|36-preInit
    /**
     * Returns an initialized instance of BROADstringItem component.
     *
     * @return the initialized component instance
     */
    public StringItem getBROADstringItem() {
        if (BROADstringItem == null) {//GEN-END:|36-getter|0|36-preInit
            // write pre-init user code here
            BROADstringItem = new StringItem("Broadcast:", "");//GEN-LINE:|36-getter|1|36-postInit
            // write post-init user code here
        }//GEN-BEGIN:|36-getter|2|
        return BROADstringItem;
    }
//</editor-fold>//GEN-END:|36-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: VALIDOstringItem ">//GEN-BEGIN:|37-getter|0|37-preInit
    /**
     * Returns an initialized instance of VALIDOstringItem component.
     *
     * @return the initialized component instance
     */
    public StringItem getVALIDOstringItem() {
        if (VALIDOstringItem == null) {//GEN-END:|37-getter|0|37-preInit
            // write pre-init user code here
            VALIDOstringItem = new StringItem("\u00C9 v\u00E1lido?", "");//GEN-LINE:|37-getter|1|37-postInit
            // write post-init user code here
        }//GEN-BEGIN:|37-getter|2|
        return VALIDOstringItem;
    }
//</editor-fold>//GEN-END:|37-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|31-getter|0|31-preInit
    /**
     * Returns an initialized instance of backCommand component.
     *
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|31-getter|0|31-preInit
            // write pre-init user code here
            backCommand = new Command("Voltar", Command.BACK, 0);//GEN-LINE:|31-getter|1|31-postInit
            // write post-init user code here
        }//GEN-BEGIN:|31-getter|2|
        return backCommand;
    }
//</editor-fold>//GEN-END:|31-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem ">//GEN-BEGIN:|38-getter|0|38-preInit
    /**
     * Returns an initialized instance of stringItem component.
     *
     * @return the initialized component instance
     */
    public StringItem getStringItem() {
        if (stringItem == null) {//GEN-END:|38-getter|0|38-preInit
            // write pre-init user code here
            stringItem = new StringItem("ATEN\u00C7\u00C3O!", "Insira valores no formato \'111.222.333.444\' e n\u00E3o ultrapasse o valor de 255 em cada casa separada por pontos!");//GEN-LINE:|38-getter|1|38-postInit
            // write post-init user code here
        }//GEN-BEGIN:|38-getter|2|
        return stringItem;
    }
//</editor-fold>//GEN-END:|38-getter|2|

    /**
     * Returns a display instance.
     *
     * @return the display instance.
     */
    public Display getDisplay() {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable(null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started. Checks whether the MIDlet have been
     * already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet();
        } else {
            initialize();
            startMIDlet();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     *
     * @param unconditional if true, then the MIDlet has to be unconditionally
     * terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }
}
